<template>
  <div class="module_">
    <div class="mb8 search_box flex-space-between">
      <el-form label-width="80px" inline autocomplete="off">
        <el-form-item label="自动备份">
          <el-switch v-model="settingObj.status"  active-color="#67C23A" @change="switchChange"> </el-switch>
        </el-form-item>
        <el-form-item class="ml16" v-show="settingObj.status">
          <el-popover placement="bottom" trigger="manual" v-model="settingObj.popover">
            <el-tabs tab-position="left"  v-model="settingObj.type">
              <el-tab-pane label="每天" name="day">
                <el-form label-width="50px">
                  <el-form-item label="时间">
                    <el-time-picker
                      size="medium"
                      v-model="settingObj.day"
                      format="HH:mm"
                      value-format="HH:mm"
                      placeholder="时间">
                    </el-time-picker>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              <el-tab-pane label="每周" name="week">
                <el-form label-width="50px">
                  <el-form-item label="周">
                    <el-select v-model="settingObj.week" size="medium" placeholder="请选择" clearable>
                        <el-option
                        v-for="item in weekArr"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="时间">
                    <el-time-picker
                      size="medium"
                      v-model="settingObj.day"
                      format="HH:mm"
                      value-format="HH:mm"
                      placeholder="时间">
                    </el-time-picker>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              <el-tab-pane label="每月" name="month">
                <el-form label-width="50px">
                  <el-form-item label="月">
                    <el-select v-model="settingObj.month" size="medium" placeholder="请选择" clearable>
                        <el-option
                        v-for="item in monthArr"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="时间">
                    <el-time-picker
                      size="medium"
                      v-model="settingObj.day"
                      format="HH:mm"
                      value-format="HH:mm"
                      placeholder="时间">
                    </el-time-picker>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
            </el-tabs>
            <div class="tx-r">
                <el-button size="medium" @click="settingObj.popover = false">取 消</el-button>
                <el-button size="medium" type="primary" @click="settingSubmit" :loading='settingLoading'>确 定</el-button>
            </div>
            <el-button slot="reference" round size="medium" type="success" @click="settingObj.popover = true">自动执行时间<i class="el-icon-arrow-down el-icon--right"/></el-button>
          </el-popover>
        </el-form-item>
      </el-form>
      <div >
        <span class="mr16"><svg class="icon f-20" aria-hidden="true" slot="image">
          <use xlink:href="#icon-tishi"></use>
        </svg>温馨提示：仅保留最近5次备份记录。</span>
        <el-button type="primary" size="medium" @click="nowRecords" :loading='nowBtnLoading'>立即备份</el-button>
      </div>
    </div>
    <el-table
      :data="tableData"
      size="medium"
      class="flex-1"
      height="150"
      border
      highlight-current-row
      v-loading="tableLoading"
      stripe
      @sort-change="tableSortChange">
      <el-table-column
        align="center"
        prop="file_name"
        label="文件名"
        width="300">
        <template slot-scope="scope">
          <svg class="icon f-20" aria-hidden="true" slot="image">
            <use xlink:href="#icon-SQLshengjiwenjian"></use>
          </svg>
          <!-- <span class="shou xialine" @click="uploadFiles(scope.row.file_path,scope.row.file_name)">{{scope.row.file_name}}</span> -->
          <a :href="uploadUrl + scope.row.file_path" :download="scope.row.file_name">{{scope.row.file_name}}</a>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="created_at"
        label="备份时间"
        width="250">
      </el-table-column>
      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="medium" @click="handle(scope.row,1)">恢复</el-button>
          <el-button size="medium" @click="handle(scope.row,2)" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination> -->
  </div>
</template>

<script>
import {
  ApibackupSetting,
  ApigetSetting,
  Apibackup,
  ApiupLoadFiles,
  ApibackupRestore,
  ApibackupRestoreDel,
  ApibackupNow
} from "@/api";
import { debounce } from "@/utils";
import {uploadUrl} from '@/api/request.js'
export default {
  data() {
    return {
      uploadUrl:uploadUrl(),
      settedObj:{},
      settingObj:{
        status: false,
        week: null,
        month: null,
        day: null,
        popover: false,
        type: 'day'
      },
      settingLoading: false,
      nowBtnLoading: false,
      tableData: [],
      pageparm: {
        page: 1,
        perPage: 20,
        total: null,
        sort_str: null,
        sort_order: null,
      },
      tableLoading: false,

      weekArr:[
        {label:'星期一',value:1},
        {label:'星期二',value:2},
        {label:'星期三',value:3},
        {label:'星期四',value:4},
        {label:'星期五',value:5},
        {label:'星期六',value:6},
        {label:'星期天',value:7},
      ],
      monthArr:[]
    };
  },
  watch:{
    'settingObj.type'(value){
        this.settingClear()
        if(value === this.settedObj.type){
            this.settingObj = {...this.settingObj,...this.settedObj}
        }
    },
    'settingObj.popover'(flag){
        if(!flag && !this.settedObj.status){
            this.settingObj.status = false
        }
    }
  },
  mounted() {
    for(let i = 1; i <= 31; i++){
        this.monthArr.push({
            label: i + '号',
            value: i
        })
    }
    //获取设置
    this.getSetting()
    this.getList();
  },
  methods: {
    nowRecords(){
      this.nowBtnLoading = true
      ApibackupNow({
        timeout: 1 * 60 * 60 * 1000,
      }).then(res => {
        this.$message.success('立即备份成功！')
        this.getList();
        this.nowBtnLoading = false
      }).catch(()=>{
        this.$message.error('立即备份失败！')
        this.nowBtnLoading = false
      })
    },
    // uploadFiles(url,name){
    //   ApiupLoadFiles(url).then(res => {
    //     let a = document.createElement("a")
    //     a.href = URL.createObjectURL(res)
    //     a.download = name
    //     a.click()
    //     URL.revokeObjectURL(a.href)
    //   })
    // },
    handle(value,i){
      let tip
      let api
      switch (i) {
        case 1:
          tip = '恢复'
          api = ApibackupRestore
          break;
        case 2:
          tip = '删除'
          api = ApibackupRestoreDel
          break;
      }
      this.$confirm(`此操作将${tip}该数据, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        api(value.id,{
          timeout: 1 * 60 * 60 * 1000,
        }).then((res) => {
          this.getList();
          this.$message({
            type: "success",
            message: tip + "成功!",
          });
        }).finally(()=>{
          loading.close()
        });
      }).catch(() => {
        this.$message({
        type: "info",
        message: "已取消" + tip,
        });
      });
    },
    switchChange(flag){
      if(!flag && this.settedObj.status){
        ApibackupSetting({status: false}).then(res => {
          this.$message.success('已成功关闭自动备份数据！')
          this.settingClear()
          this.getSetting()
        }).catch(()=>{
          this.settingObj.status = !flag
          this.$message.error('关闭自动备份数据失败，请稍后重试！')
        })
      } 
      this.$nextTick(()=>{
        this.settingObj.popover = flag
      })
    },
    settingClear(){
      this.settingObj.week = null
      this.settingObj.month = null
      this.settingObj.day = null
    },
    getSetting(show){
      // this.settingClear()
      ApigetSetting().then(res => {
        const data = JSON.parse(res.data ?? '{}')
        this.settedObj = data
        this.settingObj = {...this.settingObj,...data}
      }).finally(()=>{
        if(show)this.settingObj.popover = false
      })
    },
    settingSubmit: debounce(function(){
        const {type,day,month,week } = this.settingObj
        if(type === 'month' && !month){
          this.$message.error("请选择每月几号！");
          return
        }
        if(type === 'week' && !week){
          this.$message.error("请选择周几！");
          return
        }
        if(!day){
          this.$message.error("请选择时间！");
          return
        }
        this.settingLoading = true
        const options = {
            status: true,
            day,
            month,
            week,
            type:type
        }
        ApibackupSetting(options).then(res => {
          this.$message.success('已成功开启自动备份数据！')
          this.settingLoading = false
          this.getSetting(true)
        }).catch(()=>{
          //this.settingObj.status = false
          this.settingLoading = false
          this.$message.error('开启自动备份数据失败，请稍后重试！')
        })
    },500,true),

    tableSortChange(column) {
      if (column.order === "descending") {
        this.pageparm.sort_str = column.prop;
        this.pageparm.sort_order = "desc";
      } else if (column.order === "ascending") {
        this.pageparm.sort_str = column.prop;
        this.pageparm.sort_order = "asc";
      } else {
        this.pageparm.sort_str = null;
        this.pageparm.sort_order = null;
      }
      this.getList();
    },
    //分页
    callFather(pageparm) {
      this.pageparm.page = pageparm.page;
      this.pageparm.perPage = pageparm.perPage;
      this.getList();
    },
    getList() {
      this.tableLoading = true;
      Apibackup(this.pageparm)
        .then(({ data, page }) => {
          this.tableData = data || [];
          this.pageparm.total = page.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
  },
};
</script>